﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Configuration;
using MySql.Data.MySqlClient;


namespace h1
{
    public partial class Form_schedule : Form
    {
        string id;
        Dictionary<int, string> listItems = new Dictionary<int, string>();
        public Form_schedule()
        {
            InitializeComponent();
            //comboBox1.SelectedIndex = 0;

            ////// 从配置文件中加载保存的项
            ////LoadSavedItems();

        }
        public Form_schedule(string id)
        {
            InitializeComponent();
            this.id = id;
            button1.Enabled = false;
        }
        ////private void LoadSavedItems()
        ////{
        ////    string savedItems = ConfigurationManager.AppSettings["SavedItems"];
        ////    if (!string.IsNullOrEmpty(savedItems))
        ////    {
        ////        string[] items = savedItems.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        ////        comboBox1.Items.AddRange(items);
        ////    }
        ////}

        private void btnAdd_Click(object sender, EventArgs e)
        {

            if (tbToDo.Text == ""|| tbToDo.Text == "请输入行程标题...")
            {
                DialogResult erorr = System.Windows.Forms.MessageBox.Show("请输入日程标题！", "提示", MessageBoxButtons.OK);
            }
            else if (textBox1.Text == "" || textBox1.Text == "请输入行程说明...")
            {
                DialogResult erorr = System.Windows.Forms.MessageBox.Show("请输入行程说明！", "提示", MessageBoxButtons.OK);
            }
            else if (!(radioButton1.Checked || radioButton2.Checked || radioButton3.Checked))
            {
                DialogResult erorr = System.Windows.Forms.MessageBox.Show("请选择日程紧急情况！", "提示", MessageBoxButtons.OK);
            }

            else if (dateTimePicker1.Value >= dateTimePicker2.Value)
            {
                DialogResult erorr = System.Windows.Forms.MessageBox.Show("结束时间应在开始时间之后！", "提示", MessageBoxButtons.OK);
            }
            else if (comboBox1.Text == "")
            {
                DialogResult erorr = System.Windows.Forms.MessageBox.Show("请选择日程清单！", "提示", MessageBoxButtons.OK);
            }
            else
            {
                DataSet ds = MySqlHelper.getDataSet(MySqlHelper.Conn, $"SELECT * FROM arrangements WHERE userID = '{id}'");
                string arrid = "000000000000000";
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (dr["arrID"].ToString().Substring(dr["arrID"].ToString().Length-15).CompareTo(arrid) > 0)
                    {
                        arrid = dr["arrID"].ToString().Substring(dr["arrID"].ToString().Length - 15);
                    }
                }
                DataRow newrow = ds.Tables[0].NewRow();
                newrow["userID"] = id;
                newrow["listID"] = listItems[comboBox1.SelectedIndex];
                newrow["arrStartTime"] = dateTimePicker1.Value;
                newrow["arrEndTime"] = dateTimePicker2.Value;
                newrow["arrTitle"] = tbToDo.Text;
                newrow["arrMessage"] = textBox1.Text;
                newrow["arrOver"] = false;
                newrow["arrID"] = listItems[comboBox1.SelectedIndex]+(Convert.ToUInt32(arrid) + 1).ToString().PadLeft(15, '0');
                if (radioButton2.Checked)
                {
                    newrow["arrEmergency"] = 3;
                }
                else if (radioButton1.Checked)
                {
                    newrow["arrEmergency"] = 2;
                }
                else if (radioButton3.Checked)
                {
                    newrow["arrEmergency"] = 1;
                }
                ds.Tables[0].Rows.Add(newrow);
                MySqlHelper.updateDataSet(MySqlHelper.Conn, $"SELECT * FROM arrangements WHERE userID = '{id}'", ds);
                DialogResult sss = System.Windows.Forms.MessageBox.Show("日程创建成功！", "提示", MessageBoxButtons.OK);
                this.Close();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbToDo.ResetText();
            textBox1.ResetText();
            
        }

        private void newcomboBoxItems_Click(object sender, EventArgs e)
        {
            Form_createList form_CreateList = new Form_createList(id);
            form_CreateList.ShowDialog();
            loadLists();
        }
        private void loadLists()
        {
            comboBox1.Items.Clear();
            listItems.Clear();
            DataSet ds_lists = MySqlHelper.getDataSet(MySqlHelper.Conn, $"SELECT * FROM lists WHERE userID = '{id}'");
            if (ds_lists.Tables[0].Rows.Count < 1)
            {
                DataRow newRow = ds_lists.Tables[0].NewRow();
                newRow["userID"] = id;
                newRow["listID"] = id + "00001";
                newRow["listName"] = "默认";
                ds_lists.Tables[0].Rows.Add(newRow);
                MySqlHelper.updateDataSet(MySqlHelper.Conn, $"SELECT * FROM lists WHERE uerID = '{id}'", ds_lists);
            }
            foreach (DataRow row in ds_lists.Tables[0].Rows)
            {
                comboBox1.Items.Add(row["listName"].ToString());
                listItems.Add(comboBox1.Items.Count - 1, row["listID"].ToString());
                //Console.WriteLine($"k:{comboBox1.Items.Count - 1} v:{row["listID"].ToString()}");
            }
        }
        private void Form_schedule_Load(object sender, EventArgs e)
        {
            btn_Add.Focus();
            tbToDo.ForeColor = SystemColors.GrayText;
            textBox1.ForeColor = SystemColors.GrayText;
            textBox1.GotFocus += textBox1_GotFocus;
            textBox1.LostFocus += textBox1_LostFocus;
            tbToDo.GotFocus += tbToDo_GotFocus;
            tbToDo.LostFocus += tbToDo_LostFocus;
            tbToDo.Text = "请输入行程标题...";
            tbToDo.ForeColor = SystemColors.GrayText;
            textBox1.Text = "请输入行程说明...";
            textBox1.ForeColor = SystemColors.GrayText;
            loadLists();

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void textBox1_GotFocus(object sender, EventArgs e)
        {
            // 当文本框获得焦点时，清空默认文字并设置颜色为黑色
            if (textBox1.Text == "请输入行程说明...")
            {
                textBox1.Text = "";
                textBox1.ForeColor = Color.Black;
            }
        }

        private void textBox1_LostFocus(object sender, EventArgs e)
        {
            // 当文本框失去焦点时，检查是否有输入内容，如果没有则显示默认文字并设置颜色为灰色
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                textBox1.Text = "请输入行程说明...";
                textBox1.ForeColor = SystemColors.GrayText;
            }
        }

        private void tbToDo_GotFocus(object sender, EventArgs e)
        {
            // 当文本框获得焦点时，清空默认文字并设置颜色为黑色
            if (tbToDo.Text == "请输入行程标题...")
            {
                tbToDo.Text = "";
                tbToDo.ForeColor = Color.Black;
            }
        }

        private void tbToDo_LostFocus(object sender, EventArgs e)
        {
            // 当文本框失去焦点时，检查是否有输入内容，如果没有则显示默认文字并设置颜色为灰色
            if (string.IsNullOrWhiteSpace(tbToDo.Text))
            {
                tbToDo.Text = "请输入行程标题...";
                tbToDo.ForeColor = SystemColors.GrayText;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            try
            {
                using (MySqlConnection connection = new MySqlConnection(MySqlHelper.Conn))
                {
                    connection.Open();
                    using (MySqlCommand cmd = new MySqlCommand
                       ($"delete from lists where userID= '{id}' and listID = '{listItems[comboBox1.SelectedIndex]}'", connection))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }

            }catch(Exception ex)
            {
                Form_message fm =new Form_message("数据删除失败！","错误描述："+ex.Message);
                fm.ShowDialog();
            }
            loadLists();
            button1 .Enabled = false;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(comboBox1.Items.Count > 0)
            {
                button1.Enabled= true;
            }
        }
    }
}

